package com.sanshi.project.assets.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sanshi.project.admin.api.dto.ContractDTO;
import com.sanshi.project.admin.api.entity.CodeRuleEntity;
import com.sanshi.project.admin.api.entity.ContractEntity;
import com.sanshi.project.assets.service.CodeRuleService;
import com.sanshi.project.assets.service.ContractService;
import com.sanshi.project.common.core.util.R;
import com.sanshi.project.common.excel.annotation.ResponseExcel;
import com.sanshi.project.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 租赁合同
 *
 * @author nikon
 * @date 2023-11-27 08:46:34
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/contract")
@Tag(description = "contract", name = "租赁合同管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ContractController {

    private final ContractService contractService;
    private final CodeRuleService codeRuleService;

    /**
     * 分页查询
     *
     * @param page     分页对象
     * @param contract 租赁合同
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('assets_contract_view')")
    public R getContractPage(@ParameterObject Page page, @ParameterObject ContractDTO contract) {
        LambdaQueryWrapper<ContractEntity> wrapper = Wrappers.lambdaQuery();
        // 合同编号
        wrapper.like(StrUtil.isNotBlank(contract.getCode()), ContractEntity::getCode, contract.getCode());
        // 合同名称
        wrapper.like(StrUtil.isNotBlank(contract.getName()), ContractEntity::getName, contract.getName());
        // 租赁起始日期
        if (ArrayUtil.isNotEmpty(contract.getStartDate()))
            wrapper.ge(ContractEntity::getStartDate, contract.getStartDate()[0]).le(ContractEntity::getStartDate, contract.getStartDate()[1]);
        // 租赁结束日期
        if (ArrayUtil.isNotEmpty(contract.getEndDate()))
            wrapper.ge(ContractEntity::getEndDate, contract.getEndDate()[0]).le(ContractEntity::getEndDate, contract.getEndDate()[1]);
        // 建筑面积
        if (ArrayUtil.isNotEmpty(contract.getFloorArea()))
            wrapper.ge(ContractEntity::getFloorArea, contract.getFloorArea()[0]).le(ContractEntity::getFloorArea, contract.getFloorArea()[1]);
        // 租赁面积
        if (ArrayUtil.isNotEmpty(contract.getUseArea()))
            wrapper.ge(ContractEntity::getUseArea, contract.getUseArea()[0]).le(ContractEntity::getUseArea, contract.getUseArea()[1]);
        // 应收金额
        if (ArrayUtil.isNotEmpty(contract.getMustAmt()))
            wrapper.ge(ContractEntity::getMustAmt, contract.getMustAmt()[0]).le(ContractEntity::getMustAmt, contract.getMustAmt()[1]);
        // 实收金额
        if (ArrayUtil.isNotEmpty(contract.getPaiedAmt()))
            wrapper.ge(ContractEntity::getPaiedAmt, contract.getPaiedAmt()[0]).le(ContractEntity::getPaiedAmt, contract.getPaiedAmt()[1]);
        // 保证金
        if (ArrayUtil.isNotEmpty(contract.getForegift()))
            wrapper.ge(ContractEntity::getForegift, contract.getForegift()[0]).le(ContractEntity::getForegift, contract.getForegift()[1]);
        // 承租户姓名
        wrapper.like(StrUtil.isNotBlank(contract.getLesseeName()), ContractEntity::getLesseeName, contract.getLesseeName());
        // 承租户手机号
        wrapper.like(StrUtil.isNotBlank(contract.getLesseeTelephone()), ContractEntity::getLesseeTelephone, contract.getLesseeTelephone());
        // 催缴方式
        wrapper.in(ArrayUtil.isNotEmpty(contract.getCallType()), ContractEntity::getCallType, contract.getCallType());
        // 合同状态
        wrapper.in(ArrayUtil.isNotEmpty(contract.getStatus()), ContractEntity::getStatus, contract.getStatus());
        // 支付周期
        wrapper.in(ArrayUtil.isNotEmpty(contract.getPayCycle()), ContractEntity::getPayCycle, contract.getPayCycle());
        return R.ok(contractService.page(page, wrapper));
    }

    /**
     * 通过id查询租赁合同
     *
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('assets_contract_view')")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(contractService.getByIdDeep(id));
    }

    /**
     * 新增租赁合同
     *
     * @param contract 租赁合同
     * @return R
     */
    @Operation(summary = "新增租赁合同", description = "新增租赁合同")
    @SysLog("新增租赁合同")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('assets_contract_add')")
    public R save(@RequestBody ContractEntity contract) {
        CodeRuleEntity codeRuleEntity = new CodeRuleEntity();
        codeRuleEntity.setType("40");
        R<String> resultCode = codeRuleService.generateCode(codeRuleEntity);
        if (resultCode.isOk()) {
            // 赋予合同编码
            contract.setCode(resultCode.getData());
        } else {
            return resultCode;
        }
        // 新增合同状态默认草签（"1"）
        contract.setStatus("1");
        return R.ok(contractService.saveDeep(contract));
    }

    /**
     * 修改租赁合同
     *
     * @param contract 租赁合同
     * @return R
     */
    @Operation(summary = "修改租赁合同", description = "修改租赁合同")
    @SysLog("修改租赁合同")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('assets_contract_edit')")
    public R updateById(@RequestBody ContractEntity contract) {
        return R.ok(contractService.updateDeep(contract));
    }

    /**
     * 通过id删除租赁合同
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除租赁合同", description = "通过id删除租赁合同")
    @SysLog("通过id删除租赁合同")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('assets_contract_del')")
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(contractService.removeDeep(ids));
    }

    /**
     * 通过id删除租赁合同子表数据
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除租赁合同子表数据", description = "通过id删除租赁合同子表数据")
    @SysLog("通过id删除租赁合同子表数据")
    @DeleteMapping("/child")
    @PreAuthorize("@pms.hasPermission('assets_contract_del')")
    public R removeChild(@RequestBody Long[] ids) {
        return R.ok(contractService.removeChild(ids));
    }

    /**
     * 导出excel 表格
     *
     * @param contract 查询条件
     * @param ids      导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('assets_contract_export')")
    public List<ContractEntity> export(ContractEntity contract, Long[] ids) {
        return contractService.list(Wrappers.lambdaQuery(contract).in(ArrayUtil.isNotEmpty(ids), ContractEntity::getId, ids));
    }
}